import $ from 'jquery'

export default ({
  state: {
    id: '',
    username: '',
    photo: '',
    followerCount: 0,
    token: '',
    is_login: false,
  },
  getters: {
  },
  mutations: {
    updateUser(state, user) {
        state.id = user.id;
        state.username = user.username;
        state.photo = user.photo;
        state.followerCount = user.followerCount;
        state.is_login = user.is_login;
    },

    updateToken(state, token) {
        state.token = token;
    },
    
    logout(state) {
        state.id = '';
        state.username = '';
        state.photo = '';
        state.followerCount = 0;
        state.token = '';
        state.is_login = false;

    }
  },
  actions: {
    login(context, data) {
        $.ajax({
            url: 'http://127.0.0.1:3005/user/account/token/',
            type: 'post',
            data: {
                username: data.username,
                password: data.password,
            },
            success(resp) {
                if(resp.error_message === "success") {
                    localStorage.setItem("token", resp.token);
                    context.commit("updateToken", resp.token);
                    data.success();
                }else {
                    data.error();
                }
            }
        })
    },

    getinfo(context, data) {
        $.ajax({
            url: 'http://127.0.0.1:3005/user/account/info/',
            type: 'get',
            headers: {
                Authorization: "Bearer " + context.state.token,
            },
            success(resp) {
                if(resp.error_message === "success") {
                    context.commit("updateUser", {
                        ...resp,
                        is_login: true,
                    })
                    data.success();
                }
                
            }
        })
    },

    logout(context) {
        localStorage.removeItem('token');
        context.commit("logout");
    }
  },
  modules: {
  }
})